package com.djl.homework;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author djl
 * @Time 2024/9/29 17:08
 */
public class Ex1 {
    private static final String JSON_1 = "[{\"id\":1,\"name\":\"旗木卡卡西\",\"age\":\"31\",\"skill\":\"千年杀\"}," +
        "{\"id\":2,\"name\":\"宇智波鼬\",\"age\":\"21\",\"skill\":\"月读\"}," +
        "{\"id\":3,\"name\":\"波风水门\",\"age\":\"28\",\"skill\":\"飞雷神之术\"}," +
        "{\"id\":4,\"name\":\"迈特凯\",\"age\":\"30\",\"skill\":\"八门遁甲\"}," +
        "{\"id\":5,\"name\":\"我爱罗\",\"age\":\"16\",\"skill\":\"沙瀑送葬\"}," +
        "{\"id\":6,\"name\":\"奈良鹿丸\",\"age\":\"16\",\"skill\":\"影子模仿术\"}," +
        "{\"id\":7,\"name\":\"日向雏田\",\"age\":\"16\",\"skill\":\"柔拳\"}]";

    private static final String JSON_2 = "[{\"id\":8,\"name\":\"山中井野\",\"age\":\"16\",\"skill\":\"心转身之术\"}," +
            "{\"id\":9,\"name\":\"秋道丁次\",\"age\":\"16\",\"skill\":\"肉弹战车\"}," +
            "{\"id\":10,\"name\":\"犬冢牙\",\"age\":\"16\",\"skill\":\"牙通牙\"}," +
            "{\"id\":11,\"name\":\"油女志乃\",\"age\":\"16\",\"skill\":\"寄坏虫\"}," +
            "{\"id\":12,\"name\":\"天天\",\"age\":\"16\",\"skill\":\"操具·天锁祭\"}," +
            "{\"id\":13,\"name\":\"李洛克\",\"age\":\"16\",\"skill\":\"莲华\"}," +
            "{\"id\":14,\"name\":\"春野樱\",\"age\":\"16\",\"skill\":\"怪力\"}," +
            "{\"id\":15,\"name\":\"大蛇丸\",\"age\":\"50\",\"skill\":\"秽土转生\"}," +
            "{\"id\":16,\"name\":\"自来也\",\"age\":\"54\",\"skill\":\"仙人模式\"}]";
    private static final ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args) throws IOException {
        File file = new File("text1.txt");
        if(!file.exists()){
            file.createNewFile();
        }
        Thread thread1 = new Thread(()->{
            writeToFile(JSON_1);
        });
        Thread thread2 = new Thread(()->{
            writeToFile(JSON_2);
        });
        thread1.start();
        thread2.start();
    }
    private static void writeToFile(String json) {
        lock.lock(); // 获取锁
        try (FileWriter fileWriter = new FileWriter("text1.txt", true)) { // 追加写入
            fileWriter.write(json + "\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); // 释放锁
        }
    }

}
